/*
 * Copyright 2011 Christoph Ludwig (christoph[at]chludwig.de). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.chludwig.ehumanities.provenance.resources;

import java.io.InputStream;
import java.net.URI;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.chludwig.ehumanities.provenance.entities.LogEntry;
import de.chludwig.ehumanities.provenance.jaxb.LogEntryMetadataType;
import de.chludwig.ehumanities.provenance.jaxb.LogEntryType;
import de.chludwig.ehumanities.provenance.jaxb.ObjectFactory;

/**
 * (Sub-)Resource that represents a {@link LogEntry}.
 */
public class LogEntryResource {

  public static final Logger LOG = LoggerFactory.getLogger(LogEntryResource.class);

  public static final String DATA_PATH = "data";

  private LogEntry logEntry;

  public LogEntryResource(LogEntry entry) {
    logEntry = entry;
  }

  /**
   * @return the logEntry
   */
  public LogEntry getLogEntry() {
    return logEntry;
  }

  /**
   * @param logEntry
   *          the logEntry to set
   */
  protected void setLogEntry(LogEntry logEntry) {
    this.logEntry = logEntry;
  }

  @GET
  @Produces(MediaType.APPLICATION_XML)
  public Response getLogEntryXML(@Context UriInfo uriInfo) {
    URI dataLocator = uriInfo.getRequestUriBuilder().path(DATA_PATH).build();

    LogEntry entry = getLogEntry();
    LogEntryType entryType = new LogEntryType();
    entryType.setDataLocator(dataLocator.toASCIIString());
    entryType.setMetadata(entry.getMetadata());
    JAXBElement<LogEntryType> responseEntity = new ObjectFactory().createLogEntry(entryType);
    CacheControl noCache = ProvenanceApplication.noCacheControl();
    LOG.info("GET [{}] entry {} in container {}", new Object[] { MediaType.APPLICATION_XML, entry.getEntryId(),
        entry.getContainer().getContainerId() });
    return Response.ok(responseEntity, MediaType.APPLICATION_XML).cacheControl(noCache).build();
  }

  @GET
  @Path(DATA_PATH)
  public Response getData() {
    LogEntry entry = getLogEntry();
    InputStream is = entry.getDataStream();
    LogEntryMetadataType metadata = entry.getMetadata();
    MediaType mediaType = metadata.getMediaType();
    CacheControl noCache = ProvenanceApplication.noCacheControl();
    LOG.info("GET [{}] data of entry {} in container {}", new Object[] { mediaType, entry.getEntryId(),
        entry.getContainer().getContainerId() });
    return Response.ok(is, mediaType).cacheControl(noCache).build();
  }

  @PUT
  @Path(DATA_PATH)
  @Produces(MediaType.TEXT_PLAIN)
  public void putData(@Context HttpHeaders headers, InputStream dataStream) {
    MediaType mediaType = headers.getMediaType();
    if (mediaType == null) {
      mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
    }
    LogEntry entry = getLogEntry();
    entry.updateData(mediaType, dataStream);
    LOG.info("PUT [{}] data of entry {} in container {}", new Object[] { mediaType, entry.getEntryId(),
            entry.getContainer().getContainerId() });
  }
}
